package com.suo.enroll.controller;

import com.suo.enroll.entry.Msg;
import com.suo.enroll.service.IMsgService;
import com.suo.enroll.utils.FileUtil;
import com.suo.enroll.utils.OpenAIUtil;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@RestController
public class MsgController {
    @Resource
    private IMsgService msgService;

    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("id") Integer id) throws IOException {
        File convFile = new File(System.getProperty("java.io.tmpdir") + "/" + file.getOriginalFilename());
        convFile.createNewFile();

        // 将 MultipartFile 的内容写入临时文件
        try (FileOutputStream fos = new FileOutputStream(convFile)) {
            fos.write(file.getBytes());
        }
        String pdfText = FileUtil.extractTextFromPdf(convFile);
        // 如果 PDF 没有有效文本，返回错误
        if (pdfText.trim().isEmpty()) {
            return ResponseEntity.ok("PDF中没有有效文本！");
        }
        Msg msg = msgService.getById(id);
        msg.setMsg(pdfText);
        msgService.updateById(msg);
        // 发送请求给 OpenAI，并获取生成的摘要
        return ResponseEntity.ok(OpenAIUtil.getOpenAIResponse(pdfText,null));
    }


    @PostMapping("/prompt")
    public ResponseEntity<String> prompt(@RequestParam("id") Integer id,@RequestParam("prompt") String prompt) throws IOException {

        Msg msg = msgService.getById(id);
        String message = msg.getMsg();

        // 发送请求给 OpenAI，并获取生成的摘要
        return ResponseEntity.ok(OpenAIUtil.getOpenAIResponse(message,prompt));
    }

    @GetMapping("/msgs")
    public ResponseEntity<List<Msg>> getAllMsgs() {
        List<Msg> msgs = msgService.list();
        for (Msg msg : msgs){
            System.out.println(msg);
        }
        System.out.println(msgs.toString());
        return ResponseEntity.ok(msgs);
    }

    @GetMapping("/getOne/{msgId}")
    public ResponseEntity<Msg> getOne(@PathVariable Integer msgId) {
        return ResponseEntity.ok(msgService.getById(msgId));
    }



}
